import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { useStore } from "vuex";
import Home from "../views/Home.vue";
import Login from "../views/login/index.vue";
import Theme from "../views/Theme.vue";

const routes: Array<RouteRecordRaw> = [
  { path: "/", component: Home, meta: { requiresAuth: true, title: "首页" } },
  { path: "/login", component: Login, meta: { title: "登录" } },
  { path: "/theme", component: Theme, meta: { title: "主题" } },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 添加日志记录
router.afterEach((to) => {
  console.log(`Navigated to ${to.path}`);
});

// 全局守卫
router.beforeEach((to, from, next) => {
  console.log(`Navigating from ${from.path} to ${to.path}`);
  const store = useStore();
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!store.state.isLoggedIn) {
      next({ path: "/login" });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
